package jobs

import (
	"errors"

	"youbei/dao"
	dbtools "youbei/utils/database"
	filedump "youbei/utils/file"

	_ "github.com/denisenkom/go-mssqldb"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
)

// ExecBackup 执行备份操作
func ExecBackup(task *dao.Task) (string, error) {
	// 生成文件名
	dist, distZip := dbtools.GenerateFileNames(task)

	// 如果启用了zip密码，则设置密码
	zipPassword := ""
	if task.Enablezippwd == 1 {
		zipPassword = task.Zippwd
	}

	// 根据不同的数据库类型，执行不同的备份操作
	switch task.DBType {
	case "mysql":
		// 执行mysql备份
		if err := dbtools.MysqlCmdDump(task, dist); err != nil {
			return "", err
		}
	case "postgres":
		// 执行postgres备份
		if err := dbtools.PGSQLCmdDump(task, dist); err != nil {
			return "", err
		}
	case "mssql":
		// 执行mssql备份
		if err := dbtools.MSSQLCmdDump(task, dist); err != nil {
			return "", err
		}
	case "mongodb":
		// 执行mongodb备份
		if err := dbtools.MONGOCmdDump(task, dist); err != nil {
			return "", err
		}
	case "file":
		// 执行文件备份
		return filedump.FileDump(task.DBpath, task.SavePath, zipPassword)
	default:
		// 数据库类型不支持，返回错误
		return "", errors.New("Unsupported DBType")
	}

	// 执行SQL文件的压缩操作
	return dbtools.SQLDumpZip(dist, distZip, zipPassword)
}
